import React, { Component } from 'react';
import { Row, Col, Tag, Input, Tooltip, Icon } from 'antd';
import PropTypes from 'prop-types';

import API from '../../../api/files/index';

import './TabFileDetail.scss';

const { Search } = Input;

class TabFileDetail extends Component {
  constructor (props) {
    super(props);
    this.state = {
      file: props.file,
      inputVisible: false,
      inputValue: '',
      tags: props.file.tags,
      fileNameInputVisible: false,
    };
  }

  componentDidMount () {
    var param = {};
    this.props.callback(param);
  }

  handleClose = async (removedTag) => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    const response = await API.modifyFile({ fileId: this.state.file.id, tags });
    const { code } = response;
    if (code === 1) {
      var param = {};
      param.tags = tags;
      this.props.callback(param);
      this.setState({ tags: tags});
    }
  }
  
  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  }
  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  }
  handleInputConfirm = async () => {
    const { state } = this;
    const { inputValue } = state;
    let { tags } = state;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue];
    }
    const response = await API.modifyFile({ fileId: this.state.file.id, tags });
    const { code } = response;
    if (code === 1) {
      var param = {};
      param.tags = tags;
      this.props.callback(param);
      this.setState({
        tags:tags,
        inputVisible: false,
        inputValue: '',
      });
      console.log(this.state.tags);
    }
  }
  toggleInput = () => {
    const { fileNameInputVisible } = this.state;
    this.setState({ fileNameInputVisible: !fileNameInputVisible });
  }
  handleModifyFileName = async (value) => {
    const response = await API.modifyFile({ fileId: this.state.file.id, nickname: value });
    const { code } = response;
    if (code === 1) {
      this.setState({
        file: Object.assign({}, this.state.file, { nickname: value }),
        fileNameInputVisible: false,
      });
      var param = {};
      param.fileName = value;
      this.props.callback(param);
    }
  }
  render () {
    const {
      file, inputVisible, inputValue, tags,
    } = this.state;
    Date.prototype.Format = function (fmt) { //author: meizz 
      var o = {
          "M+": this.getMonth() + 1, //月份 
          "d+": this.getDate(), //日 
          "h+": this.getHours(), //小时 
          "m+": this.getMinutes(), //分 
          "s+": this.getSeconds(), //秒 
          "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
          "S": this.getMilliseconds() //毫秒 
      };
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
  }
  var unixTimestamp = new Date(file.createdMillis);
  var commonTime = unixTimestamp.Format("yyyy-MM-dd hh:mm:ss");  
  var updateTime = new Date(file.updatedMillis);
  var updatedTime = updateTime.Format("yyyy-MM-dd hh:mm:ss");  
    const { style } = this.props; //eslint-disable-line
    return (
      <div className="tab-wrapper-file-detail-view" style={style}>
        <Row>
          <Col span={6} className="tab-wrapper-label">文件名：</Col>
          <Col span={18}>
            {
              this.state.fileNameInputVisible ?
              (
                <Search
                  defaultValue={file.nickname}
                  onSearch={this.handleModifyFileName}
                  enterButton="保存"
                />
              ) :
                <span>{file.nickname}.{file.format}</span>
            }
            {
              !this.state.fileNameInputVisible && <Icon type="edit" onClick={this.toggleInput} style={{ cursor: 'pointer', marginLeft: 20 }} />
            }
          </Col>
        </Row>
        <Row>
          <Col span={6} className="tab-wrapper-label">创建人：</Col>
          <Col span={18}><span>{file.createdBy.nickname}</span></Col>
        </Row>
        <Row>
          <Col span={6} className="tab-wrapper-label">创建时间：</Col>
          <Col span={18}><span>{commonTime}</span></Col>
        </Row>
        <Row>
          <Col span={6} className="tab-wrapper-label">版本号：</Col>
          <Col span={18}><span>{file.version.sequence}</span></Col>
        </Row>
        <Row>
          <Col span={6} className="tab-wrapper-label">上传人：</Col>
          <Col span={18}><span>{file.createdBy.nickname}</span></Col>
        </Row>
        <Row>
          <Col span={6} className="tab-wrapper-label">更新时间：</Col>
          <Col span={18}><span>{updatedTime}</span></Col>
        </Row>
        <Row>
          <Col span={6} className="tab-wrapper-label">标签：</Col>
          <Col span={18}>
            <span>
              {
                tags.map((tag) => {
                  const isLongTag = tag.length > 10;
                  const tagElem = (
                    <Tag key={tag} closable afterClose={() => this.handleClose(tag)}>
                      {isLongTag ? `${tag.slice(0, 10)}...` : tag}
                    </Tag>
                  );
                  return isLongTag ? <Tooltip title={tag} key={tag}>{tagElem}</Tooltip> : tagElem;
                })
              }
              {
                inputVisible && (
                  <Input
                    ref={(input) => { this.input = input; }}
                    type="text"
                    size="small"
                    style={{ width: 78 }}
                    value={inputValue}
                    onChange={this.handleInputChange}
                    onBlur={this.handleInputConfirm}
                    onPressEnter={this.handleInputConfirm}
                  />
                )
              }
              {
                !inputVisible && (
                  <Tag
                    onClick={this.showInput}
                    style={{ background: '#fff', borderStyle: 'dashed' }}
                  >
                    <Icon type="plus" />添加标签
                  </Tag>
                )
              }
            </span>
          </Col>
        </Row>
      </div>
    );
  }
}

TabFileDetail.propTypes = {
  file: PropTypes.object.isRequired,
  callback: PropTypes.func.isRequired,
};

export default TabFileDetail;
